import { nanoid } from 'nanoid'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getImgUrl, download, removeStorage, getStorage, setStorage, STORAGE_FABRIC_KEY } from './tools'

/**
 * 右边按钮操作
 * @param {*} param0 
 * @returns 
 */
export const useSaveImg = ({
  canvasRef,
  fileList,
  currentTplId,
  dialogImageUrl,
  dialogVisible,
}) => {
  // 名
  const tplNameRef = ref('')
  // 取消选中元素并获取画布url
  const discardActiveAndGetUrl = () => {
    canvasRef.value.discardActiveObject()
    canvasRef.value.renderAll()

    const url = getImgUrl()
    return url
  }
  // 画布预览
  const handlePreview = () => {
    const url = discardActiveAndGetUrl()
    dialogImageUrl.value = url
    dialogVisible.value = true
  }

  // 下载图片
  const handleDownload = async () => {
    const url = discardActiveAndGetUrl()
    await download(url, nanoid(8) + '.png')
    ElMessage.success('下载完成')
  }

  // 清除画布
  const handleClear = (noTips = true) => {
    canvasRef.value.clear()
    canvasRef.value.backgroundColor = 'rgba(255, 255, 255, 1)'
    canvasRef.value.renderAll()
    noTips && ElMessage.success('已清除')
  }

  // 新建画布
  const handleCreate = () => {
    // 先清除
    handleClear(false)
    currentTplId.value = ''
    ElMessage.success('新建成功')
  }

  // 保存到模板
  const handleSaveTpl = async () => {
    await ElMessageBox.confirm('是否保存到模板？', '提示', {
      confirmButtonText: '保存',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // const isUpdate = currentTplId.value === '' ? false : true

    const name = tplNameRef.value || nanoid(8) // 备用
    const id = currentTplId.value || nanoid(8)
    // 画布json
    const json = canvasRef.value.toDatalessJSON()

    // 图片url  base64
    const url = discardActiveAndGetUrl()

    // 组合
    const data = { json, id, name, url }

    // 将 json 和图片 一起存到 localStorage
    const storage = getStorage(STORAGE_FABRIC_KEY)
    storage[id] = data
    setStorage(STORAGE_FABRIC_KEY, storage)

    const index = fileList.value.findIndex(item => item.id === currentTplId.value)
    if (index > -1) {
      fileList.value.splice(index, 1, data)
    } else {
      fileList.value.push(data)
    }

    ElMessage.success('保存成功')
  }

  return {
    handlePreview,
    handleDownload,
    handleSaveTpl,
    handleClear,
    handleCreate,
  }
}
